package com.ermax.aircond.maintain.web.bean;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.imageio.ImageIO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ermax.aircond.maintain.domain.Building;
import com.ermax.aircond.maintain.domain.Floor;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.domain.Room;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.web.bean.DataTableBean;

@Scope("view")
@Component
public class FloorPlanMaintainBean implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(FloorPlanMaintainBean.class);
	@Autowired
	private MaintainService maintainService;	
	@ManagedProperty(value = "#{loginBean.sessionUser}")
	private String sessionUser;
	
	private List<Machine> machines = new ArrayList<Machine>();
	
	private List<SelectItem> buildingOptions = new ArrayList<SelectItem>();
	private List<SelectItem> floorOptions = new ArrayList<SelectItem>();
	private Floor selectedFloor = null;
	private long selectedBuildingId;
	private long selectedFloorId;

	@PostConstruct
	public void init() {
		try {			
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	private void reset() throws Exception {		
		buildingOptions = createBuildingOptions();
		floorOptions = createFloorOptions();		
	}
		
	private List<SelectItem> createBuildingOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();	
		results.add(new SelectItem(0,"----"));
		try {
			List<Building> buildings = maintainService.getAllBuildings();
			for (Building building : buildings) {
				SelectItem item = new SelectItem(building.getBuildingId(), building.getBuildingName());
				results.add(item);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}		

		return results;
	}
	
	private List<SelectItem> createFloorOptions(){		
		List<SelectItem> results = new ArrayList<SelectItem>();		
		results.add(new SelectItem(0,"----"));
		try{
			if(selectedBuildingId > 0){
				Building selectedBuilding = maintainService.getBuildingById(selectedBuildingId);
				List<Floor> floors = maintainService.getFloors(selectedBuilding);
	        	for(Floor floor : floors){
	        		SelectItem item = new SelectItem(floor.getFloorId(), floor.getFloorName());
	        		results.add(item);
	        	}
			}
		}catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		
		return results;
		
	}
	
	public void buildingValueChanged(ValueChangeEvent event) {      
        if (null != event.getNewValue()) {   
        	selectedFloorId = 0;
            selectedBuildingId = (Long) event.getNewValue();
            floorOptions = createFloorOptions();
        }
    }
	
	
	public void select() {
		try{						
			if(selectedFloorId > 0){
				selectedFloor = maintainService.getFloorDetail(selectedFloorId);
				machines = maintainService.getMachines(selectedFloor);
			}			
		}catch(Exception ex){}
	}
		
	
	public void uploadListener(FileUploadEvent event) throws Exception {
        UploadedFile item = event.getUploadedFile();
        if(selectedFloor != null){
        	selectedFloor.setFloorPlan(item.getData());
        	maintainService.updateFloor(selectedFloor, sessionUser);
        }        
    }
	

	public void paint(OutputStream out, Object data) throws IOException {
		if(selectedFloor != null){
			out.write(selectedFloor.getFloorPlan());
			out.close();
		}		
	}

	public List<Machine> getMachines() {
		return machines;
	}

	public void setMachines(List<Machine> machines) {
		this.machines = machines;
	}

	public List<SelectItem> getBuildingOptions() {
		return buildingOptions;
	}

	public void setBuildingOptions(List<SelectItem> buildingOptions) {
		this.buildingOptions = buildingOptions;
	}

	public List<SelectItem> getFloorOptions() {
		return floorOptions;
	}

	public void setFloorOptions(List<SelectItem> floorOptions) {
		this.floorOptions = floorOptions;
	}

	public long getSelectedBuildingId() {
		return selectedBuildingId;
	}

	public void setSelectedBuildingId(long selectedBuildingId) {
		this.selectedBuildingId = selectedBuildingId;
	}

	public long getSelectedFloorId() {
		return selectedFloorId;
	}

	public void setSelectedFloorId(long selectedFloorId) {
		this.selectedFloorId = selectedFloorId;
	}

	public String getSessionUser() {
		return sessionUser;
	}

	public void setSessionUser(String sessionUser) {
		this.sessionUser = sessionUser;
	}

	public Floor getSelectedFloor() {
		return selectedFloor;
	}

	public void setSelectedFloor(Floor selectedFloor) {
		this.selectedFloor = selectedFloor;
	}

		
}
